package com.dy.yunying.biz.config;

import com.pig4cloud.pig.api.util.NoRepeatSubmit;
import com.pig4cloud.pig.common.core.util.R;
import com.pig4cloud.pig.common.security.util.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

/**
 * @author yuwenfeng
 * @description: 校验重复提交切面
 * @date 2021/11/10 9:58
 */
@Aspect
@Component
@Slf4j
public class CheckRepeatSubmitAop {

	@Autowired
	private RedisTemplate<String, String> redisTemplate;

	@Around("execution(* com.dy.yunying.biz.controller.hongbao.*Controller.*(..)) && @annotation(nrs)")
	public Object arround(ProceedingJoinPoint pjp, CheckRepeatSubmit nrs) {
		ValueOperations<String, String> opsForValue = redisTemplate.opsForValue();
		try {
			ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
			Integer userId = SecurityUtils.getUser().getId();
			HttpServletRequest request = attributes.getRequest();
			System.out.println("userId:" + userId);
			String key = userId + "-" + request.getServletPath();
			if (opsForValue.get(key) == null) {// 如果缓存中有这个url视为重复提交
				Object o = pjp.proceed();
				opsForValue.set(key, "0", 3, TimeUnit.SECONDS);
				return o;
			} else {
				log.error("重复提交");
				return R.failed("提交太频繁，请稍后操作");
			}
		} catch (Throwable e) {
			e.printStackTrace();
			log.error("验证重复提交时出现未知异常{}", e.getMessage());
			return R.failed("验证重复提交时出现异常");
		}
	}
}
